package chapter6;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;

//LC 71

/**
 *先split，然后遍历，遇到"" "." 和 " "都跳过
 * 遇到".."stack.pop, 否则stack.push
 * 最后反转stack，string.join
 * 最左加上根路径/
 */
public class SimplifyPath {
    public String simplifyPath(String path) {
        LinkedList<String> stack = new LinkedList<>();
        String[] arr = path.split("/");
        System.out.println(Arrays.toString(arr));
        for (String s : arr) {
            if (s.equals(" ") || s.equals(".") || s.equals("")) continue;
            if (s.equals("..")){
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            }else {
                stack.push(s);
            }
        }
        System.out.println(stack);
        Collections.reverse(stack);
        String res = String.join("/", stack);
        return "/"+res;
    }

    public static void main(String[] args) {
        String res = new SimplifyPath().simplifyPath("/home//foo/");
        System.out.println(res);
    }
}
